<?php
require_once dirname(__FILE__) . '/../db/_orm/orm.inc.php';
require_once dirname(__FILE__) . '/../DbUtils.class.php';
require_once dirname(__FILE__) . '/../includes/MiscUtils.class.php';

$renamed = true;
$overwrite = true; 
$max = 999999999999; 

if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
  //获得上传文件信息
  $upload_file = $_FILES['Filedata'];
  //获取文件扩展名
  $file_info = pathinfo($upload_file['name']);
  $file_ext = (isset($file_info['extension'])) ? $file_info['extension'] : '';
  
  //获取客户端参数
  $query = json_decode($_POST['query']);
  $product_track_id = ($query && isset($query->pti)) ? $query->pti : 0;
  $is_creating_thumbnail = ($query && isset($query->t)) ? $query->t : false;
  
  //设置上传的路径
  //建立文件夹
  $updir = 'uploads/products/';
  $upload_path = $updir . $product_track_id . '/';
  create($upload_path);
  
  $unique_id = $upload_file['name'];
  $path = $upload_path . $upload_file['name'];
  //需要重命名否?
  if($renamed){
    $unique_id = 'f' . (time() * rand());
    $path = $upload_path . $unique_id . '.' . $file_ext;
    $path_tn = $upload_path . $unique_id . '_tn.jpg';
    $path_small = $upload_path . $unique_id . '_small.jpg';
  }
  
  //检查文件是否存在
  if (file_exists($path)) {
    if($overwrite) {
      @unlink($path);
    } else {
      $j = 0;
      do {
        $j++;
        $tmp = str_replace('.' . $file_ext, '(' . $j . ').' . $file_ext, $path);
      }
      while (file_exists($temp_file));
      $path = $tmp;
      unset($tmp);
      unset($j);
    }
  }
  
  if ($upload_file['size'] && $upload_file['size'] < $max && $is_creating_thumbnail) {
    if (strtolower($file_ext) == 'jpg' || strtolower($file_ext) == 'jpeg') {
      $im = imagecreatefromjpeg($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'png') {
      $im = imagecreatefrompng($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'gif') {
      $im = imagecreatefromgif($upload_file["tmp_name"]);
    }
    if ($im) {
      $width = imagesx($im);
      $height = imagesy($im);
      
      if (file_exists($path_small)) {
        unlink($path_small);
      }
      ResizeImage($im, 200, 200, "$upload_path$unique_id". '_small');
      ImageDestroy($im);
    } else {
      exit(0);
    }
  }
  
  if ($upload_file['size'] && $upload_file['size'] < $max && $is_creating_thumbnail) {
    if (strtolower($file_ext) == 'jpg' || strtolower($file_ext) == 'jpeg') {
      $im = imagecreatefromjpeg($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'png') {
      $im = imagecreatefrompng($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'gif') {
      $im = imagecreatefromgif($upload_file["tmp_name"]);
    }
    if ($im) {
      $width = imagesx($im);
      $height = imagesy($im);
      
      if (file_exists($path_tn)) {
        unlink($path_tn);
      }
      ResizeImage($im, 80, 80, "$upload_path$unique_id". '_tn');
      ImageDestroy($im);
    } else {
      exit(0);
    }
  }
  
  if (move_uploaded_file($upload_file['tmp_name'], $path)) {
    //Add custom code here...
    if (strtolower($file_ext) == 'jpg' || strtolower($file_ext) == 'jpeg') {
      $im = imagecreatefromjpeg($path);
    } else if (strtolower($file_ext) == 'png') {
      $im = imagecreatefrompng($path);
    } else if (strtolower($file_ext) == 'gif') {
      $im = imagecreatefromgif($path);
    }
    $width = NULL;
    $height = NULL;
    if (isset($im)) {
      $width = imagesx($im);
      $height = imagesy($im);
    }
    
    try {
      $myPdo = DbUtils::createPdoInst();
      $myPdo->exec('UPDATE `pz_ecom_product` SET `date_last_mod` = \'' . date("Y-m-d H:i:s") . '\' WHERE `track_id` = \'' . $product_track_id . '\'');
      
      $file = new stdClass();
      $file->track_id = MiscUtils::unique();
      $file->product_track_id = $product_track_id;
      $file->name = $upload_file['name'];
      $file->name_on_server = $unique_id;
      $file->size = ($upload_file['size']) ? $upload_file['size'] : 0;
      $file->width = $width;
      $file->height = $height;
      $file->path = $path;
      $file->path_small = $path_small;
      $file->path_tn = $path_tn;
      $file->is_default = 0;
      DbUtils::add($myPdo, 'pz_ecom_product_image', $file);
      $file->id = $myPdo->lastInsertId();
      echo json_encode($file);
    } catch (PDOException $ex) {
      echo ERROR_SIGN . $ex->getMessage();
    }
  }
} 
  
//若没有这个文件夹，则需要创建文件夹
function create($dir) {
  if (!is_dir($dir)) {
    $temp = explode('/',$dir);
    $cur_dir = '';
    for($i = 0; $i < count($temp); $i++) {
      $cur_dir .= $temp[$i].'/';
      if (!is_dir($cur_dir)) {
        @mkdir($cur_dir, 0777);
      }
    }
  }
}

function ResizeImage($im, $maxwidth, $maxheight, $name){
  $width = imagesx($im);
  $height = imagesy($im);
  if (($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)) {
    $RESIZEWIDTH = false;
    $RESIZEHEIGHT = false;
    if ($maxwidth && $width > $maxwidth) {
      $widthratio = $maxwidth/$width;
      $RESIZEWIDTH = true;
    }
    if ($maxheight && $height > $maxheight) {
      $heightratio = $maxheight/$height;
      $RESIZEHEIGHT = true;
    }
    if ($RESIZEWIDTH && $RESIZEHEIGHT) {
      if ($widthratio < $heightratio) {
        $ratio = $widthratio;
      } else {
        $ratio = $heightratio;
      }
    } else if ($RESIZEWIDTH) {
      $ratio = $widthratio;
    } else if ($RESIZEHEIGHT) {
      $ratio = $heightratio;
    }
    $newwidth = $width * $ratio;
    $newheight = $height * $ratio;
    if (function_exists("imagecopyresampled")) {
      $newim = imagecreatetruecolor($newwidth, $newheight);
      imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    } else {
      $newim = imagecreate($newwidth, $newheight);
      imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    }
    imagejpeg($newim, $name . ".jpg");
    imagedestroy($newim);
  } else {
    imagejpeg($im, $name . ".jpg");
  }
}
?>